<?php
/**
 * Created by PhpStorm.
 * User: Sky
 * Date: 16/12/9
 * Time: 下午5:13
 */


use yii\helpers\Url;

$web = Url::base();
$this->title = '子机构(部门)管理';
$scriptUrl = \Yii::$app->request->scriptUrl;
$url = \app\librarys\Tools::urlBase();
?>

<script type="application/javascript">
    var institution;
    var institutions; //机构列表
    var institutionCurent; //当前人员所在机构

    var department;
    var instituion_add;

    $(function ($) {
        $('#myModalEdit').modal({
            keyboard: false, backdrop: 'static', show: false
        });
//        $('#myModalDetail').modal({
//            keyboard: false, backdrop: 'static', show: false
//        });
        $('#addDepManager').modal({
            backdrop: 'static', show: false
        });
        //绑定机构

        institutions =  <?= json_encode($institutions) ?>;
        institutionCurent =<?= json_encode($institution_code) ?>;
        institution = $('#inputInstitution').treeAutocomplete({
            defaultText: '选择机构',
            source: institutions,
            onSelected: function (element) {
                filter();
            }
        }).setValue(institutionCurent);

    });

    function filter() {
        var department_name = $("#department_name").val();
        var institution_code = $("#inputInstitution").val();

        var href = window.location.href;
        var index = href.indexOf("?page=");
        if (index > 0) {
            href = href.substr(0, index);
        }
        var href_str = href + "?page=1";


        if (department_name != '' && department_name != null) {
            href_str = href_str + "&name=" + department_name;
        }

        if (institution_code != '' && institution_code != null) {
            href_str = href_str + "&institution_code=" + institution_code;
        }

        window.location.href = href_str;
    }

    function onAddData(id) {
        $("#myModalEdit").modal('show');
        var data = {};
        if (id != undefined) {
            data.id = id;
        }
        modalEdit(data);
    }

    //打开新增修改页面
    function modalEdit(data) {
        $("#modaledit").html('');
        requestHtml('department-part-view', data, true, function (responseHtml) {
            $("#modaledit").html(responseHtml);
        });
    }

    function saveData() {
        var institution_code = instituion_add.getValue();
        if (institution_code == "") {
            alert("请先选择机构");
            return false;
        }
        var parent_id = department.getValue();//在弹出窗口 获取部门
        var id = $("#modaledit_submit_form").find("#id").val();
        var name = $("#modaledit_submit_form").find("#name").val();
        var remark = $("#modaledit_submit_form").find("#remark").val();


        var data = {};
        if (name == "" || name == null) {
            $("#hint_message").text('单证开始不能为空！');
            $("#hintMessageModal").modal('show');
            return false;
        }

        data.institution_code = institution_code;
        data.parent_id = parent_id;
        data.id = id;
        data.name = name;
        data.remark = remark;

        loading.show();
        requestJson("department-save-handler", data, true, function (response) {
            if (response.status == 0) {
                filter();
            } else {
                $("#hint_message").text(response.message);
                $("#hintMessageModal").modal('show');
            }
        });
    }

    //删除按键点击事件
    function delClick(id) {
        $("#deleteDataId").val(id);
    }

    //删除取消
    function delClose() {
        $("#deleteDataId").val('');
        $("#deleteModal").modal('hide');
    }

    //删除数据
    function delData() {
        var id = $("#deleteDataId").val();
        delClose();
        if (id != null && id != '') {
            var data = {};
            data.id = id;
            requestJson("department-del-handler", data, true, function (response) {
                if (response.status == 0) {
                    $("#hint_message").text('操作成功！');
                    window.location.reload();
                } else {
                    $("#hint_message").text('操作失败！');
                }
                $("#hintMessageModal").modal('show');
            });
        } else {
            $("#hint_message").text('需删除的数据有误，请重试！');
            $("#hintMessageModal").modal('show');
        }
    }

    var doType = null;
    //添加用户
    function onAddUser(id) {
        $("#doUserData_btn").html('添加');
        doType = 'add';
        $("#departmentUserEdit").modal('show');
        var data = {};
        data.id = id;
        data.institution_code = $("#inputInstitution").val();

        $("#departmentEdit").html('');
        requestHtml('department-part-adduser-view', data, true, function (responseHtml) {
            $("#departmentEdit").html(responseHtml);
        });
    }

    //删除用户
    function onDelUser(id) {
        $("#doUserData_btn").html('移除');
        doType = 'del';
        $("#departmentUserEdit").modal('show');
        var data = {};
        data.id = id;
        data.institution_code = $("#inputInstitution").val();

        $("#departmentEdit").html('');
        requestHtml('department-part-deluser-view', data, true, function (responseHtml) {
            $("#departmentEdit").html(responseHtml);
        });
    }

    function doUserData() {
        var department_id = $("#depuser_submit_form").find("#department_id").val();
        var chks = $("#depuser_submit_form").find('input:checkbox[name=user_chk]:checked');
        if (chks.length <= 0) {
            $("#hint_message").text('请选择用户！');
            return false;
        }
        var user_array = [];
        for (var i = 0; i < chks.length; i++) {
            user_array.push($(chks[i]).val());
        }

        var data = {};
        data.department_id = department_id;
        data.user_array = user_array;
        var action = "";
        if (doType == "add") {
            action = "department-adduser-handler";
        } else if (doType == "del") {
            action = "department-deluser-handler";
        }
        requestJson(action, data, true, function (response) {
            if (response.status == 0) {
                $("#hint_message").text('操作成功！');
                window.location.reload();
            } else {
                $("#hint_message").text('操作失败！');
            }
            $("#hintMessageModal").modal('show');
        });
    }

    function addMagClick(department, departmentName, institution) {

        $("#addDepManager").modal('show');
        $("#departmentName").text(departmentName);
        $('#btnAddManagerOk').click(function () {

            var data = {};
            data.institution_code = institution;
            data.department_id = department;
            data.name = $('#inputName').val();
            data.account = $('#inputAccount').val();
            data.password = $('#inputPassword').val();
            data.phone = $('#inputPhone').val();
            data.is_enabled = $('#inputIsEnabled').val();
            data.remark = $('#inputRemark').val();
            data.role_list = [];
            $("input:checkbox[name=role]:checked").each(function () {
                data.role_list.push($(this).val());
            });
            requestJson('<?= $url ?>/system/add-manager-handler', data, true, function (responseData) {
                if (responseData.status == 0) {
                    $('#addModal').modal('hide');
                    window.location.reload();
                } else {
                    alert(responseData.message);
                }
            });
        });

    }
    function editMagClick(department, departmentName, institution) {
        $("#editDepManager").modal('show');
    }

</script>

<style type="text/css">
    .modal-body {
        overflow: auto;
        max-height: 600px;
    }
</style>


<!-- head filter-->
<div class="panel panel-default">
    <div class="panel-body">
        <div class="form-inline">
            <div class="btn-group">
                <button class="btn btn-primary" type="button" onclick="onAddData()"><i class="fa fa-plus"></i> 新增
                </button>
            </div>
            <div class="pull-right  col-lg-11">

                <div class="col-lg-3">
                    <div id="inputInstitution"></div>
                </div>

                <div class="col-lg-3">
                    <input type="text" class="form-control" id="department_name" placeholder="子机构(部门)名称"
                           value="<?= $name ?>">
                </div>
                <div class="col-lg-2">
                    <button type="button" class="btn btn-primary" onclick="filter()"><i class="fa fa-search"></i> 搜索
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- body table-->
<div class="panel panel-default" id="department_list">
    <div class="panel-body">
        <div class="table-responsive">
            <table class="table table-bordered table-hover table-condensed">
                <thead class="nowrap">
                <tr>
                    <th style="width:20%">子机构(部门)名称</th>
                    <th style="width:15%">描述</th>
                    <th style="width:15%">创建时间</th>
                    <th style="width:15%">操作</th>
                </tr>
                </thead>
                <tbody>
                <?php
                if ($list != null && count($list) > 0) {
                    for ($i = 0; $i < count($list); $i++) {
                        $list[$i]['level'] = (strlen($list[$i]['code_tree']) - 8) / 4 - 1;
                        ?>
                        <tr>
                            <td>
                                <?php
                                for ($j = 0; $j < $list[$i]['level']; $j++) {
                                    ?>
                                    &nbsp;&nbsp;&nbsp;&nbsp;
                                    <?php
                                }
                                ?>

                                <?= $list[$i]['name'] ?>
                            </td>
                            <td>
                                <?= $list[$i]['remark'] ?>
                            </td>
                            <td>
                                <?= $list[$i]['create_datetime'] ?>
                            </td>
                            <td>
                                <button class="btn btn-link btn-xs" type="button"
                                        onclick="onAddUser('<?= $list[$i]['id'] ?>')"
                                        data-toggle="modal"
                                        data-target="#departmentUserEdit">
                                    添加会员
                                </button>

                                <button class="btn btn-link btn-xs" type="button"
                                        onclick="onDelUser('<?= $list[$i]['id'] ?>')"
                                        data-toggle="modal"
                                        data-target="#departmentUserEdit">
                                    查看会员
                                </button>


                                <button class="btn btn-link btn-xs" type="button"
                                        onclick="onAddData('<?= $list[$i]['id'] ?>')"
                                        data-toggle="modal"
                                        data-target="#myModalEdit">
                                    修改
                                </button>

                                <button class="btn btn-link btn-xs" type="button"
                                        data-toggle="modal"
                                        data-target="#deleteModal"
                                        onclick="delClick('<?= $list[$i]['id'] ?>')">
                                    删除
                                </button>
                                <button class="btn btn-link btn-xs" type="button"
                                        data-toggle="modal"
                                        data-target="#addDepManager"
                                        onclick="addMagClick('<?= $list[$i]['id'] ?>','<?= $list[$i]['name'] ?>','<?= $list[$i]['institution_code'] ?>')">
                                    添加管理员
                                </button>
                                <button class="btn btn-link btn-xs" type="button"
                                        data-toggle="modal"
                                        data-target="#editDepManager"
                                        onclick="editMagClick('<?= $list[$i]['id'] ?>','<?= $list[$i]['name'] ?>','<?= $list[$i]['institution_code'] ?>')">
                                    查看管理员
                                </button>

                            </td>
                        </tr>
                        <?php
                    }
                }
                ?>
                </tbody>
            </table>
        </div>
        <div class="pull-left">
            <?= \app\widgets\LinkPagerExt::widget(['pagination' => $pagination]) ?>
        </div>
    </div>
</div>


<!-- Modal card Edit-->
<div class="modal fade" id="myModalEdit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">子机构(部门)信息</h4>
            </div>
            <div id="modaledit" class="modal-body">
            </div>
            <div class="modal-footer">
                <div>
                    <label style="text-align: left">注：当您的子机构(部门)需要由不同的成员来维护人员或发积分的时候，可以设置子机构(部门)，并分配相应的管理员。各子机构(部门)管理员可以维护本子机构(部门)的会员，或发积分。您（机构管理员）可以查看所有的会员及发分记录，子机构管理员(部门)只能查看子机构(部门)的数据</label>
                </div>
                <button type="button" class="btn btn-primary" onclick="saveData()"><i class="fa fa-save"></i> 保存
                </button>
                <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-remove"></i> 取消
                </button>
            </div>
        </div>
    </div>
</div>


<!-- Modal card Edit-->
<div class="modal fade" id="departmentUserEdit" tabindex="-1" role="dialog" aria-labelledby="departmentUserLabel">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="departmentUserLabel">子机构(部门)会员</h4>
            </div>
            <div id="departmentEdit" class="modal-body">
            </div>
            <div class="modal-footer">
                <div>
                    <label style="text-align: left">注：此处展示的会员为【会员管理】模块中维护的会员，您可以在本模块对已有会员勾选进行添加（或移除）子机构(部门)操作，也可以在【会员管理】模块向子机构(部门)新增（或移除）会员。</label>
                </div>
                <div>
                <button type="button" class="btn btn-primary" onclick="doUserData()"><i class="fa fa-save"></i> <span
                        id="doUserData_btn">确定</span>
                </button>
                <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-remove"></i> 取消
                </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!--删除确认对话框-->
<div aria-hidden="true" role="dialog" tabindex="-1" id="deleteModal" class="modal fade">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">是否确认操作？</h4>
                <input type="hidden" id="deleteDataId" class="form-control" value="">
            </div>
            <div class="modal-body" align="center">
                注意：<br>
                <span style="color: red">删除操作将删除该子机构（部门）及其下属的所有子机构（部门）！</span><br>
                <br>该子机构(部门)及其下属机构的所有用户不再隶属于这些子机构(部门)，可重新给他们分配子机构（部门）。<br>
                <br>如此子机构(部门)及其下属机构有管理员，请调整管理员权限，将管理员调整到新子机构(部门)，或禁用。<br>
            </div>
            <div class="modal-footer">
                <button class="btn btn-primary" onclick="delData()"><i class="fa fa-ok"></i> 确认</button>
                <button class="btn btn-primary" onclick="delClose()"><i class="fa fa-remove"></i> 取消</button>
            </div>
        </div>
    </div>
</div>

<!--提示对话框-->
<div aria-hidden="true" role="dialog" tabindex="-1" id="hintMessageModal" class="modal fade">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
                <h4 class="modal-title">提示</h4>
            </div>
            <div class="modal-body" id="hint_message" align="center">
            </div>
        </div>
    </div>
</div>

<!--添加子机构管理员-->
<div aria-hidden="true" role="dialog" tabindex="-1" id="addDepManager" class="modal fade">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
                <h4 class="modal-title">新增管理员</h4>
            </div>
            <div class="modal-body">
                <div class="form-horizontal">
                    <!-- <div class="form-group">
                         <label class="col-lg-3 col-sm-3 control-label">机构:</label>
                         <div class="col-lg-9">
                             <div id="inputInstitution"></div>
                         </div>
                     </div>-->

                    <!--<div class="form-group">
                        <label class="col-lg-3 col-sm-3 control-label">部门:</label>
                        <div class="col-lg-9" id="department_div">
                            <div id="inputdepartment"></div>
                        </div>
                    </div>-->
                    <div class="form-group">
                        <label class="col-lg-3 col-sm-3 control-label">子机构(部门):</label>
                        <div class="col-lg-9">
                            <label class="control-label" id="departmentName"></label>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-lg-3 col-sm-3 control-label">姓名:</label>
                        <div class="col-lg-9">
                            <input type="text" class="form-control" id="inputName"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-3 col-sm-3 control-label">账号:</label>
                        <div class="col-lg-9">
                            <input type="text" class="form-control" id="inputAccount"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-3 col-sm-3 control-label">密码:</label>
                        <div class="col-lg-9">
                            <input type="password" class="form-control" id="inputPassword"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-3 col-sm-3 control-label">手机号码:</label>
                        <div class="col-lg-9">
                            <input type="tel" class="form-control" id="inputPhone"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-3 col-sm-3 control-label">是否启用:</label>
                        <div class="col-lg-9">
                            <select class="form-control" id="inputIsEnabled">
                                <option value="1">启用</option>
                                <option value="0">禁用</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label col-lg-3">备注:</label>
                        <div class="col-lg-9">
                            <textarea rows="4" class="form-control" id="inputRemark"></textarea>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="panel">
                            <div class="panel-heading">
                                角色配置
                            </div>
                            <div class="panel-body">
                                <?php
                                //$isSystemAdmin = \app\models\Permission::isSystemAdmin();
                                foreach ($roleList as $role) {
                                    if ($role['is_department'] != 1) {
                                        continue;
                                    }
                                    ?>
                                    <div class="square-blue form-inline icheck col-lg-4">
                                        <div class="checkbox popovers" data-trigger="hover" data-placement="top"
                                             data-original-title="<?= $role['name'] ?>"
                                             data-content="<?= $role['description'] ?>">
                                            <input type="checkbox" name="role" value="<?= $role['id'] ?>" checked>
                                            <label><?= $role['name'] ?> </label>
                                        </div>
                                    </div>
                                    <?php
                                }
                                ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">关闭</button>
                <button class="btn btn-primary" id="btnAddManagerOk">确定</button>
            </div>

        </div>
    </div>
</div>

<!--查看禁用子机构管理员-->
<div aria-hidden="true" role="dialog" tabindex="-1" id="editDepManager" class="modal fade">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
                <h4 class="modal-title">提示</h4>
            </div>
            <div class="modal-body" id="eidt_message" align="center">
                功能正在开发中，敬请期待…… <br><br>请到【系统管理】——【管理员】中进行修改！
            </div>
        </div>
    </div>
</div>